var defaultPage = Public.getDefaultPage();
var config = defaultPage.CONFIG;
var system = defaultPage.SYSTEM;
var api = frameElement.api, W = api.opener;
var callback = api.data.callback,oper = api.data.oper;
var _height = $(parent).height()-192,_width = $(parent).width()-50;

var ka_state = $("#ka_state").val();
var ka_number = $("#ka_number").val();
var queryurl = config.BASEPATH+"shop/kpiassess/loadDetail/"+ka_number;
if(ka_state == '0'){//未总结
	queryurl = config.BASEPATH+"shop/kpiassess/statDetail/"+ka_number;
}

var Utils = {
	doQueryReward:function(obj,rowid,kal_code){
		commonDia = $.dialog({
			title : '选择奖励',
			content : 'url:'+config.BASEPATH+'sys/reward/to_list_dialog',
			data : {multiselect:true},
			width : 460,
			height : 340,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				var codes = [];
				var names = [];
				$(obj).parent().prev().empty();
				for (var i = 0; i < selected.length; i++) {
					codes.push(selected[i].rw_code);
					names.push(selected[i].rw_name);
//					$(obj).parent().prev().append('<i class="iconfont '+selected[i].rw_style+'" title="'+selected[i].rw_name+'">'+selected[i].rw_icon+'</i>');
				}
				$(obj).parent().prev().text(names.join(","));
				var rowData = {};
				rowData["reward_codes"+kal_code] = codes.join(",");
				$("#grid").jqGrid('setRowData', rowid, rowData);
				return true;
			},
			cancel:true
		});
	},
	doRemoveReward:function(obj,rowid,kal_code){
		$(obj).parent().prev().text("");
		var rowData = {};
		rowData["reward_codes"+kal_code] = "";
		$("#grid").jqGrid('setRowData', rowid, rowData);
	},
	doViewKpiScore:function(obj,rowid,realComplete){
		var rowData = $('#grid').jqGrid('getRowData', rowid);
		$.dialog({
			title : 'KPI指标分数查询',
			content : 'url:'+config.BASEPATH+"sys/kpi/to_view",
			data: {ki_code:rowData.kal_ki_code,realComplete:realComplete},
			width : 500,
			height : 420,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:true,
			cancel:true
		});
	}
};

var handle = {
	complete:function(){
		var params = {};
		var kpiassess = {};
		kpiassess.ka_id = $("#ka_id").val();
		kpiassess.ka_number = $("#ka_number").val();
		kpiassess.ka_summary = $("#ka_summary").val();
		var details = [];
		var ids = $("#grid").jqGrid('getDataIDs');
		for (var i = 0; i < $_details.length; i++) {
			var rowData = $_details[i];
			var lineData = $("#grid").jqGrid("getRowData", ids[i]);
			for (var j = 0; j < $_columns.length; j++) {
				var row = {};
				row.kal_id = rowData["id"+$_columns[j].kal_code];
				row.kal_code = $_columns[j].kal_code;
				row.kal_ki_code = rowData.kal_ki_code;
				row.ki_name = rowData.ki_name;
				row.kal_complete = rowData["complete"+$_columns[j].kal_code];
				row.kal_score = rowData["score"+$_columns[j].kal_code];
				row.reward_codes = lineData["reward_codes"+$_columns[j].kal_code];
				details.push(row);
			}
		}
		params.kpiassess = Public.encodeURI(JSON.stringify(kpiassess));
		params.details = Public.encodeURI(JSON.stringify(details));
		$("#btn-save").attr("disabled",true);
		$.ajax({
			type:"POST",
			url:config.BASEPATH+"shop/kpiassess/complete",
			data:params,
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
					Public.tips({type: 3, content : '总结成功'});
					handle.loadData(data.data);
				}else{
					Public.tips({type: 1, content : data.message});
				}
				$("#btn-save").attr("disabled",false);
			}
		});
		
		
	},
	loadData:function(data){
		var pdata = {};
		pdata.id=data.ka_id;
		pdata.ka_number=data.ka_number;
		pdata.ka_state=data.ka_state;
		pdata.operate='';
		if(callback && typeof callback == 'function'){
			callback(pdata,oper,window);
		}
	},
	formatReward :function(val, opt, row){
		var kal_code = opt.colModel.name.substr(6);
		var html_con = '';
		html_con += '<span class="reward">';
		html_con += $.trim(val);
		html_con += '</span>';
		if(ka_state == '0'){//未总结
			html_con += '<span class="operating" >';
			html_con += '<i class="iconfont i-hand" title="发放奖励" onclick="javascript:Utils.doQueryReward(this,'+opt.rowId+',\''+kal_code+'\');">&#x3435;</i>';
			html_con += '<i class="iconfont i-hand" title="删除" onclick="javascript:Utils.doRemoveReward(this,'+opt.rowId+',\''+kal_code+'\');">&#xe60e;</i>';
			html_con += '</span>';
		}
		return html_con;
	},
	formatComplete :function(val, opt, row){
		var html_con = '';
		html_con += '<a href="javascript:void(0);" onclick="javascript:Utils.doViewKpiScore(this,'+opt.rowId+',\''+$.trim(val)+'\');">';
		html_con += $.trim(val);
		html_con += '</a>';
		return html_con;
	}
};

var $_columns = null;
var $_details = null;

var THISPAGE = {
	init:function (){
		this.initDom();
		this.loadDetailDatas();
		this.initEvent();
	},
	initDom:function(){
		if(ka_state == '1'){//已总结
			$("#btn-save").hide();
		}
	},
	loadDetailDatas:function(){
		$.ajax({
			type:"POST",
			async:false,
			url:queryurl,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
					var detailData = data.data;
					$_columns = detailData.header;
					$_details = detailData.details;
					THISPAGE.initGrid(detailData.header,detailData.details);
				}
			}
		});
	},
	gridTotal:function(){
		var grid=$('#grid');
		var scoreMap = {};
		var footer = {};
		footer.ki_name = "总计：";
		var maxScore = 0;
		for ( var i = 0; i < $_columns.length; i++) {
			var score = parseInt(grid.getCol("score"+$_columns[i].kal_code,false,'sum'));
			footer["score"+$_columns[i].kal_code] = score;
			scoreMap[$_columns[i].kal_code] = score;
			if (score > maxScore) {
				maxScore = score;
			}
		}
    	grid.footerData('set',footer);
    	var winnerCodes = [];
		var winnerNames = [];
		if(maxScore > 0){//遍历获得获胜者
			for ( var i = 0; i < $_columns.length; i++) {
				var score = scoreMap[$_columns[i].kal_code];
				if(maxScore == score){
					winnerCodes.push($_columns[i].kal_code);
					winnerNames.push($_columns[i].kal_name);
				}
			}
		}    	
    	$("#winner").text(winnerNames.join(","));
    	$("#maxScore").text(maxScore);
	},
	buildChart:function(){
		var ids = $("#grid").getDataIDs();
    	var chartjs = '';
    	chartjs += '{';
    	chartjs += '"chart":{"type":"column","margin":75,"options3d":{"enabled":true,"alpha":45,"beta":0,"depth":50,"viewDistance":25}},';
    	chartjs += '"title":{"text":"';
    	var ka_type = $("#ka_type").val();
		switch(ka_type){
			case '0' : 
				chartjs += '店铺考核图表';
				break ;
			case '1' : 
				chartjs += '员工组考核图表';
				break ;
			case '2' : 
				chartjs += '员工考核图表';
				break ;
			default :
				break ;
		}
    	chartjs += '"},';
    	chartjs += '"xAxis":{"title":{"text":"';
    	switch(ka_type){
			case '0' : 
				chartjs += '店铺';
				break ;
			case '1' : 
				chartjs += '员工组';
				break ;
			case '2' : 
				chartjs += '员工';
				break ;
			default :
				break ;
		}
    	chartjs += '"},"categories": [';
		for ( var i = 0; i < $_columns.length; i++) {
			if(i == $_columns.length - 1){
				chartjs += '"'+$_columns[i].kal_name+'"';
			}else{
				chartjs += '"'+$_columns[i].kal_name+'",';
			}
		}
		chartjs += ']},';
		chartjs += '"yAxis": {"min": 0,"title": {"text": "总分"}},';
		chartjs += '"tooltip": {';
		chartjs += '"headerFormat": "<span style=\'font-size:13px;font-weight:bold\'>{point.key}</br></span>",';
		chartjs += '"pointFormat": "<b>{point.y:.0f}分</b>"},';
		chartjs += '"plotOptions": {"column": {"pointPadding": 0.2,"borderWidth": 0}},';
		chartjs += '"series": [';
		chartjs += '{';
		chartjs += '"name": "总分",';
		chartjs += '"data":[';
		for ( var i = 0; i < $_columns.length; i++) {
			var score = $('#grid').getCol("score"+$_columns[i].kal_code,false,'sum')
			if(i == $_columns.length - 1){
				chartjs += score;
			}else{
				chartjs += score+',';
			}
		}
		chartjs += '],';
		chartjs += '"dataLabels": { ';
		chartjs += '"enabled": false,"rotation": -45,"color": "#FFFFFF","align": "right","x": 4,"y": 10,';
		chartjs += '"style": {"fontSize": "10px","fontFamily": "Verdana, sans-serif","textShadow": "0 0 3px black"}';
		chartjs += '}}]';
		chartjs += '}';
		document.getElementById("container").style.height="300px";
    	eval("$('#container').highcharts("+chartjs+")");
	},
	initGrid:function(columns,rows){
		var colModel = [
	    	{label:'指标编号',name: 'kal_ki_code', index: 'kal_ki_code', width: 140, hidden: true},
	    	{label:'指标名称',name: 'ki_name', index: 'ki_name', width: 160, title: false}
	    ];
		if (columns != null && columns.length > 0) {
			for ( var i = 0; i < columns.length; i++) {
				colModel.push({label:'完成情况',name: "complete"+columns[i].kal_code, width: 80,align:'right',formatter: handle.formatComplete});
				colModel.push({label:'分数',name: "score"+columns[i].kal_code, width: 80,align:'right'});
				colModel.push({label:'奖励',name: "reward"+columns[i].kal_code, width: 120,formatter: handle.formatReward});
				colModel.push({label:'奖励编号',name: "reward_codes"+columns[i].kal_code, width: 100,hidden:true});
				colModel.push({label:'',name: "id"+columns[i].kal_code, width: 100,hidden:true});
			}	
		}
		$('#grid').jqGrid({
			loadonce:true, //只从后台加载一次数据，datatype被修改为local,如果弹出框想要查询则再开启为json
			datatype: 'local',
			width:_width,
			height: 220,
			altRows:true,
			gridview: true,
			onselectrow: false,
			colModel: colModel,
			rownumbers: true,//行号
			pager: '#page',//分页
			multiselect:false,//多选
			viewrecords: true,
			cmTemplate: {sortable:false,title:false},
			page: 1, //只有一页
			pgbuttons:false,
			pgtext:false,
			rowNum:999,//每页条数
			shrinkToFit:false,//表格是否自动填充
			footerrow: true,
			jsonReader: {
				root: "data",
				repeatitems : false	,
				id: 'kal_ki_code'  //图标ID
			},
			loadComplete: function(data){
				THISPAGE.gridTotal();
				THISPAGE.buildChart();
			},
			loadError: function(xhr, status, error){		
			}
	    });
		$("#grid").jqGrid('setGridParam', {datatype : 'local',data : rows}).trigger("reloadGrid");
		var groupHeaders = [];
		if (columns != null && columns.length > 0) {
			for ( var i = 0; i < columns.length; i++) {
				groupHeaders.push({startColumnName : "complete"+columns[i].kal_code,numberOfColumns : 3, titleText : columns[i].kal_name });
			}
		}
		$("#grid").jqGrid('setGroupHeaders', { 
			useColSpanStyle : true, // 没有表头的列是否与表头列位置的空单元格合并 
			groupHeaders : groupHeaders
		});
	},
	initEvent:function(){
		$("#btn_close").click(function(e){
			e.preventDefault();
			api.close();
		});
		$('#grid').on('click', '.operating .ui-icon-plus', function (e) {
            e.preventDefault();
            var id = $(this).parent().data('id');
            var ka_type = $("#ka_type").val();
			if(ka_type == '0'){
				Utils.doQueryShop();
			}else if(ka_type == '1'){
				Utils.doQueryEmpGroup();
			}else if(ka_type == '2'){
				Utils.doQueryEmp();
			}
        });
		$('#grid').on('click', '.operating .ui-icon-trash', function (e) {
            e.preventDefault();
            var id = $(this).parent().data('id');
            if(id != 0){
            	var ids = $("#grid").jqGrid('getDataIDs');
            	$.dialog.confirm('数据删除后将不能恢复，请确认是否删除？',function(){
            		$('#grid').jqGrid('delRowData', id);
            	});
            }
        });
	}
};

THISPAGE.init();